package com.ccom.user.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccom.api.domain.User;
import com.ccom.core.common.constant.CommonConstant;
import com.ccom.core.common.enums.ExceptionEnums;
import com.ccom.core.common.exception.RemindException;
import com.ccom.core.common.model.Result;
import com.ccom.core.common.util.IdWorker;
import com.ccom.core.common.util.PasswordUtil;
import com.ccom.core.common.util.StringUtils;
import com.ccom.core.common.util.oConvertUtils;
import com.ccom.user.mapper.UserMapper;
import com.ccom.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author zjj
 * @Date 2021/8/25
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IdWorker idWorker;

    @Override
    public boolean resetPassword(String username, String oldpassword, String newpassword, String confirmpassword) {
        User user = userMapper.getUserByName(username);

        if (user != null) {
            String passwordEncode = PasswordUtil.encrypt(username, oldpassword, user.getSalt());
            if (!user.getPassword().equals(passwordEncode)) {
                throw new RemindException(ExceptionEnums.USER_PASSWORD_ERROR);
            }
            if (StringUtils.isEmpty(newpassword)) {
                throw new RemindException(ExceptionEnums.USER_PASSWORD_NOT_NULL);
            }
            if (!newpassword.equals(confirmpassword)) {
                throw new RemindException(ExceptionEnums.USER_PASSWORD_SAME_OLD);
            }
            String password = PasswordUtil.encrypt(username, newpassword, user.getSalt());
            this.userMapper.update(new User().setPassword(password), new LambdaQueryWrapper<User>().eq(User::getId, user.getId()));
            log.info("resetPassword success username:{},newpassword:{}", username, password);
            return true;
        }
        return false;
    }

    @Override
    public Result<?> changePassword(User user) {
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String password = user.getPassword();
        String passwordEncode = PasswordUtil.encrypt(user.getUserName(), password, salt);
        user.setPassword(passwordEncode);
        this.userMapper.updateById(user);
        log.info("changePassword success username:{},newpassword:{}", user.getUserName(), password);
        return Result.success("密码修改成功!");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(String userId) {
        this.removeById(userId);
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatchUsers(String userIds) {
        boolean result = removeByIds(Arrays.asList(userIds.split(",")));
        return result;
    }

    @Override
    public User getUserByName(String username) {
        return userMapper.getUserByName(username);
    }

    @Override
    public User getUserByPhone(String phone) {
        return userMapper.getUserByPhone(phone);
    }


    @Override
    public User getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }


    /**
     * 校验用户是否有效(存在、注销、冻结)
     *
     * @param User
     * @return
     */
    @Override
    public void checkUserIsEffective(User User) {
        //情况1：根据用户信息查询，该用户不存在
        if (User == null) {
            throw new RemindException(ExceptionEnums.USER_NO_ACCOUNT);
        }
        //情况2：根据用户信息查询，该用户已注销
        if (CommonConstant.DEL_FLAG_1.equals(User.getDelFlag())) {
//            baseCommonService.addLog("用户登录失败，用户名:" + User.getUsername() + "已注销！", CommonConstant.LOG_TYPE_1, null);
            throw new RemindException(ExceptionEnums.USER_ACCOUNT_REMOVE);
        }
        //情况3：根据用户信息查询，该用户已冻结
        if (CommonConstant.USER_FREEZE.equals(User.getStatus())) {
//            baseCommonService.addLog("用户登录失败，用户名:" + User.getUsername() + "已冻结！", CommonConstant.LOG_TYPE_1, null);
            throw new RemindException(ExceptionEnums.USER_ACCOUNT_FREEZE);
        }
    }

    @Override
    public List<User> queryLogicDeleted() {
        return this.queryLogicDeleted(null);
    }

    @Override
    public List<User> queryLogicDeleted(LambdaQueryWrapper<User> wrapper) {
        if (wrapper == null) {
            wrapper = new LambdaQueryWrapper<>();
        }
        wrapper.eq(User::getDelFlag, CommonConstant.DEL_FLAG_1);
        return userMapper.selectLogicDeleted(wrapper);
    }

    @Override
    public boolean revertLogicDeleted(List<String> userIds, User updateEntity) {
        String ids = String.format("'%s'", String.join("','", userIds));
        return userMapper.revertLogicDeleted(ids, updateEntity) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeLogicDeleted(List<String> userIds) {
        String ids = String.format("'%s'", String.join("','", userIds));
        // 1. 删除用户
        int line = userMapper.deleteLogicDeleted(ids);
        return line != 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateNullPhoneEmail() {
        userMapper.updateNullByEmptyString("email");
        userMapper.updateNullByEmptyString("phone");
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(User user) {
        user.setId(idWorker.nextId());
        this.save(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editUser(User user) {
        //step.1 修改用户基础信息
        this.updateById(user);
    }

    @Override
    public List<String> userIdToUsername(Collection<String> userIdList) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(User::getId, userIdList);
        List<User> userList = super.list(queryWrapper);
        return userList.stream().map(User::getUserName).collect(Collectors.toList());
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.selectList(null);
    }
}
